from django.http import HttpResponse
from django.shortcuts import render

from testmodel.models import Test


def save_test(request):
    test = Test(name='test', age=18, email='test@test.com')
    test.save()
    return HttpResponse('save success')


def get_test(request):
    test = Test.objects.get(id=1)
    return HttpResponse(test.name)


def delete_test(request):
    test = Test.objects.get(id=1)
    test.delete()
    return HttpResponse('delete success')


def update_test(request):
    test = Test.objects.get(id=2)
    test.name = 'test2'
    test.save()
    return HttpResponse('update success')


def get_test_filter(request):
    # 初始化
    response = ""
    response1 = ""

    tests = Test.objects.filter(name='test', age=18).order_by('-id')
    for test in tests:
        response1 += str(test.id) + " " + test.name + " " + str(test.age) + " " + test.email + "<br>"
    response += response1

    # tests = Test.objects.filter(name__contains='t').order_by('-id')
    return HttpResponse(response)


def search_form(request):
    return render(request, 'testdb/search_form.html')


def search_test(request):
    request.encoding = 'utf-8'
    message = 'message'
    # if request.method == 'POST':
    #     q = request.POST.get('q')
    #     message = '搜索结果：' + q
    # else:
    #     message = '你的请求方式为GET，请使用POST方式提交搜索内容'
    return HttpResponse(message)
